<template>
  <!-- 日常管理 -->
  <div class="app-container horizontal">
    <el-row :gutter="40">
      <el-col v-show="fold" class="headRowClass" :span="4" :xs="24">
        <!-- 左侧企业列表城市菜单树 -->
        <div class="head-container">
          <el-input
            v-model="cityName"
            placeholder="请输入城市名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
          />
        </div>
        <div class="head-container">
          <el-tree
            ref="tree"
            :data="cityOptions"
            node-key="label"
            :props="defaultProps"
            :expand-on-click-node="false"
            :default-expand-all="false"
            :filter-node-method="filterNode"
            :highlight-current="currentColor"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="fold === true?20:24" :xs="24" class="right-content">
        <el-col v-if="fold" :span="1">
          <el-row class="treeStyle el-tree-arrow">
            <i class="el-icon-arrow-left" @click="fold = false" />
          </el-row>
        </el-col>
        <el-col v-if="!fold" :span="1">
          <el-row type="flex" justify="center" class="treeStyle2 el-tree-arrow">
            <i class="el-icon-arrow-right" @click="fold = true" />
          </el-row>
        </el-col>
        <div class="form-container">
          <!-- 右侧搜索栏 -->
          <el-form
            ref="topForm"
            :inline="true"
            label-width="80px"
            :model="filters"
            class="selectFrom"
            style="text-align:left"
          >
            <el-row>
              <el-form-item label="企业名称" prop="name">
                <el-input v-model="filters.name" size="small" clearable placeholder="请输入企业名称" />
              </el-form-item>
              <el-form-item label="企业状态" prop="status">
                <el-select
                  v-model="filters.status"
                  placeholder="请选择企业状态"
                  clearable
                  size="small"
                >
                  <el-option
                    v-for="dict in statusOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="企业类型" prop="enterpriseType">
                <el-select
                  v-model="filters.enterpriseType"
                  placeholder="请选择企业类型"
                  clearable
                  size="small"
                >
                  <el-option
                    v-for="dict in enterpriseTypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <slot name="label">
                  <i class="highLevelStyle" :class="highLevelSet===true?'el-icon-arrow-up':'el-icon-arrow-down'" @click="highLevelSet = !highLevelSet" />
                </slot>
              </el-form-item>
            </el-row>
            <el-row v-if="highLevelSet">
              <el-form-item label="到期天数" prop="dateDay">
                <el-input v-model.number="filters.dateDay" size="small" clearable placeholder="到期天数" />
              </el-form-item>
              <el-form-item label="到期时间" prop="enterpriseExpiryTime">
                <el-date-picker
                  v-model="filters.enterpriseExpiryTime"
                  size="small"
                  class="date"
                  clearable
                  type="date"
                  style="width:200px;"
                  value-format="yyyy-MM-dd"
                  placeholder="选择到期时间"
                />
              </el-form-item>
              <el-form-item label="创建时间" prop="dateRange">
                <el-date-picker
                  v-model="dateRange"
                  size="small"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  style="width:225px;"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  clearable
                />
              </el-form-item>
            </el-row>
          </el-form>
        </div>
        <!-- 功能按钮 -->
        <el-row :gutter="10" class="button-wrap">
          <el-col :span="1.5">
            <el-button v-clickForbidden icon="el-icon-search" size="middle" @click="handleQuery">搜索</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-clickForbidden icon="el-icon-refresh" size="middle" @click="resetQuery()">重置</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:sysEnterprise:resetPwd']" icon="el-icon-refresh" :disabled="ispassword" size="middle" @click="passwordReset">密码重置</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:sysEnterprise:updateEnterpriseMenu']" :disabled="isAmendTime" icon="el-icon-edit" size="middle" @click="amendTime">修改到期时间</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:sysEnterprise:updateEnterpriseMenu']" :disabled="isMenuTime" icon="el-icon-edit" size="middle" @click="changeMenuTime">修改菜单时间</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="el-icon-s-home" :disabled="isInitialize" size="middle" @click="initialise">初始化信息</el-button>
          </el-col>
          <el-col v-hasPermi="['system:sysEnterprise:edit']" :span="1.5">
            <el-button v-show="status === '0'" size="middle" :disabled="isStart" icon="el-icon-star-off" @click="handleStatusChange">
              停用
            </el-button>
          </el-col>
          <el-col v-hasPermi="['system:sysEnterprise:edit']" :span="1.5">
            <el-button v-show="status === '1'" size="middle" :disabled="isStart" icon="el-icon-star-on" @click="handleStatusChange">
              启用
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button :disabled="isLook" icon="el-icon-zoom-in" size="middle" @click="lookBtn">详情</el-button>
          </el-col>
        </el-row>
        <!-- 企业表格数据 -->
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="tableData"
          class="table-list"
          stripe
          :class="highLevelSet===true ? (needTagsView===true ? 'el-body-page-roll-tag-height' : 'el-body-page-roll-height') :
            (needTagsView===true ? 'el-body-page-roll-tag' : 'el-body-page-roll')"
          style="width: 100%;"
          :row-style="rowColor"
          @selection-change="selectionChange"
          @row-click="rowChecked"
        >
          <el-table-column type="selection" width="38" align="center" />
          <el-table-column type="index" label="序号" width="51" align="center" />
          <el-table-column label="企业名称" show-overflow-tooltip prop="name" align="center" min-width="200" />
          <el-table-column label="企业性质" show-overflow-tooltip prop="nature" align="center" min-width="140" :formatter="statusFormat" />
          <el-table-column label="联系人" prop="contacts" align="center" min-width="100" show-overflow-tooltip />
          <el-table-column label="联系电话" prop="phone" align="center" show-overflow-tooltip min-width="150" />
          <!-- <el-table-column label="企业类型" prop="enterpriseType" align="center" min-width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.enterpriseType === '0'">一般企业</span>
              <span v-if="scope.row.enterpriseType === '2'">监管单位</span>
            </template>
          </el-table-column> -->
          <el-table-column prop="enterpriseType" :formatter="(row) => formatterSysEnterpriseType(row)" label="企业类型" align="center" min-width="80" />
          <!-- <el-table-column label="单位类型" prop="sysEnterpriseType" align="center" min-width="120" :formatter="(row) => formatterSysEnterpriseType(row)" />
          <el-table-column prop="seller" label="销售代表" min-width="100" align="center" /> -->
          <el-table-column label="企业状态" min-width="80" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.status === '0'">正常</span>
              <span v-if="scope.row.status === '1'">停用</span>
            </template>
          </el-table-column>
          <el-table-column label="审核状态" min-width="100" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.checkStatus === '0'">审核成功</span>
              <span v-if="scope.row.checkStatus === '1'">审核成功</span>
              <span v-if="scope.row.checkStatus === '2'">未审核</span>
              <span v-if="scope.row.checkStatus === '3'">初始化成功</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip width="180" /> -->
        </el-table>
        <!-- 分页 -->
        <pagination
          :total="total"
          :page.sync="filters.pageNum"
          :limit.sync="filters.pageSize"
          @pagination="getList"
        />
        <!-- 初始化信息 -->
        <Initalize ref="initalize" />
        <!--  查看按钮对话框 -->
        <Details ref="details" :city-options="cityOptions" />
        <!-- 修改使用时间对话框 -->
        <ExpiryTime ref="expiryTime" />
        <!-- 企业修改菜单时间 -->
        <enverday-change-menus v-if="menuVisible" ref="changeMenus" />

      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapState } from 'vuex'
// 加载企业修改菜单时间子组件
import EverdayChangeMenus from './components/index'
import Initalize from './components/Initialize'
import Details from './components/Details'
import ExpiryTime from './components/ExpiryTime'
import { listRegionTree } from '@/api/common/area'
import { resetPwd, listDaily, changeStatusByIds } from '@/api/enterprise/everday'
import { getDicts } from '@/api/system-tool/dict/data'
import { listNoPermission } from '@/api/superviseBaseInfo/typeManage/organizationType'
export default {
  name: 'Everday',
  components: {
    'enverday-change-menus': EverdayChangeMenus, Initalize, ExpiryTime, Details
  },
  data() {
    return {
      EnterpriseType: [], // 单位类型
      // 城市树选中高亮
      currentColor: false,
      // 加载等待样式
      loading: false,
      // 城市树折叠
      fold: true,
      // 修改按钮不显示
      isShow: false,
      // 查看的id
      idPrint: '',
      // 表格数据总数
      total: 0,
      // 分页条目
      filters: {
        province: '',
        city: '',
        status: '0',
        name: '',
        pageNum: 1,
        pageSize: this.fristPageSize,
        enterpriseType: '',
        legalperson: '',
        dateDay: '',
        enterpriseExpiryTime: '',
        seller: ''
      },
      // 时间范围
      dateRange: [],
      // 企业状态选项
      statusOptions: [],
      // 修改按钮是否可用
      isAmend: true,
      // 密码重置按钮是否可用
      ispassword: true,
      // 修改使用时间是否可用
      isAmendTime: true,
      // 修改企业时间是否可用
      isMenuTime: true,
      // 启用按钮是否可用
      isStart: true,
      // 查看按钮是否可用
      isLook: true,
      // 初始化信息按钮是否可用
      isInitialize: true,
      // 搜索城市名称表单
      cityName: '',
      // 高级设置显示与否
      highLevelSet: false,
      // 企业类型选项
      enterpriseTypeOptions: [{ dictValue: '', dictLabel: '全部' }],
      // 企业列表树数据
      cityOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 表格数据
      tableData: [],
      // 表格选中项
      multipleSelection: [],
      selectRow: [],
      status: '0',
      // 加载树形菜单结构
      defaultrops: {
        children: 'children',
        label: 'label'
      },
      // 企业修改菜单时间
      menuVisible: false,
      natureData: []
    }
  },
  computed: {
    ...mapState({
      needTagsView: state => state.settings.tagsView
    }),
    // 高级搜索显示隐藏
    handleTagShow() {
      return this.highLevelSet
    }
  },
  watch: {
    cityName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.loadCityOptions()
    getDicts('sys_dept_status').then(resp => {
      this.statusOptions = resp.data.rows
    })
    getDicts('enterprise_type').then(resp => {
      this.enterpriseTypeOptions = { ...this.enterpriseTypeOptions, ...resp.data.rows }
    })
    this.getDicts('enterprise_nature').then(response => {
      this.natureData = response.data.rows
    })
  },
  mounted() {
    this.getList()
    this.listEnterpriseType()
  },
  methods: {
    // 获取单位类型
    async  listEnterpriseType() {
      const { data: { rows }} = await listNoPermission()
      this.EnterpriseType = rows
    },
    // 回显单位类型
    formatterSysEnterpriseType(row) {
      if (row && row.enterpriseType) {
        if (row.enterpriseType === '2') {
          return '监管单位'
        }
        if (this.EnterpriseType.length < 0) return
        const items = this.EnterpriseType.filter(item => {
          return item.typeNum === row.enterpriseType
        })
        return items.length > 0 ? items[0].typeName : '-'
      }
    },
    // 项目状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.natureData, row.nature)
    },
    // 获取城市信息列表
    loadCityOptions() {
      listRegionTree().then(resp => {
        if (resp) {
          this.cityOptions = resp.data
        }
      })
    },
    // 密码重置功能
    passwordReset() {
      this.$confirm('您确定要重置密码吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const enterpriseId = this.multipleSelection[0].id
        resetPwd(enterpriseId).then(resp => {
          if (resp) {
            this.msgSuccess('密码重置成功!')
          } else {
            this.msgError(resp.message)
          }
        })
      })
        .catch(() => {
        })
    },
    // 修改使用时间按钮
    amendTime() {
      this.$refs.expiryTime.expiryTimeAdd(this.multipleSelection[0].id)
    },
    // 搜索按钮功能
    handleQuery() {
      this.getList()
    },
    // 补空白行
    addTaleData() {
      if (this.tableData.length < this.filters.pageSize) {
        const arr = {}
        this.tableData.push(arr)
        this.addTaleData()
      }
    },
    // 获取表格数据
    getList() {
      this.loading = true
      listDaily(this.changeDateRange(this.filters, this.dateRange)).then(resp => {
        if (resp) {
          this.tableData = resp.data.rows
          this.total = resp.data.total
          // this.addTaleData()
          this.loading = false
        } else {
          this.msgError(resp.message)
        }
      })
    },
    // 点击表格前复选框
    selectionChange(selection) {
      if (JSON.stringify(selection[0]) === '{}') {
        this.$refs.multipleTable.clearSelection()
        selection = []
      }
      this.multipleSelection = selection
      this.isAmend = selection.length !== 1
      this.ispassword = selection.length !== 1
      this.isAmendTime = selection.length !== 1
      this.isLook = selection.length !== 1
      this.isStart = selection.length !== 1
      this.isMenuTime = selection.length !== 1
      this.isInitialize = selection.length !== 1
      if (this.multipleSelection.length === 1) {
        this.status = this.multipleSelection[0].status
      }
      this.selectRow = []
      if (selection.length > 0) {
        selection.forEach((item, index) => {
          this.selectRow.push(this.tableData.indexOf(item))
        })
      }
      // 如果选择的数组大于1
      if (selection.length > 1) {
        // 清空所有的选中
        this.$refs.multipleTable.clearSelection()
        // 将数组的最后一个选中
        this.$refs.multipleTable.toggleRowSelection(selection.pop())
        this.$refs.multipleTable.toggleRowExpansion(selection.pop())
      }
    },
    rowColor({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { 'background-color': 'rgba(185,211,249,0.75)' }
      }
    },
    // 点击每行数据
    rowChecked(row) {
      // 将选中的数组赋给常量 selectData
      const selectData = this.multipleSelection
      // 调用表格的方法将所有已选的都取消
      this.$refs.multipleTable.clearSelection()
      // 判断选中的数组个数是不是等于 1
      if (selectData.length === 1) {
        // 循环判断有没有和当前行的相同的
        selectData.forEach(item => {	// 判断 如果当前的一行被勾选, 再次点击的时候就会取消选中
          if (item === row) {
            this.$refs.multipleTable.toggleRowSelection(row, false)
          } else {
            this.$refs.multipleTable.toggleRowSelection(row, true)
          }
        })
      } else { // 不等于1时
        this.$refs.multipleTable.toggleRowSelection(row, true)
      }
    },
    // 重置功能
    resetQuery() {
      this.resetForm('topForm')
      this.filters.province = ''
      this.filters.city = ''
      this.filters.pageNum = 1
      this.dateRange = []
      this.$refs.tree.setCurrentKey()
      this.getList()
    },
    // 修改菜单使用时间按钮
    changeMenuTime() {
      const enterpriseId = this.multipleSelection[0].id
      const subCompany = this.multipleSelection[0].id
      this.menuVisible = true
      // 调用企业修改菜单时间的组件 并传值
      this.$nextTick(() => {
        this.$refs.changeMenus.showView(enterpriseId, subCompany)
      })
    },
    // 用户状态修改
    handleStatusChange() {
      const row = this.multipleSelection[0]
      const text = row.status === '0' ? '停' : '启用'
      this.$confirm('确认要' + text + '' + row.name + '用户吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const id = this.multipleSelection[0].id
          if (row.status === '0') {
            row.status = '1'
          } else {
            row.status = '0'
          }
          const status = row.status
          changeStatusByIds(id, status).then(resp => {
            if (resp) {
              this.getList()
              this.msgSuccess('操作成功！')
            } else {
              this.msgError(resp.message)
            }
          })
        })
        .catch(() => {
        })
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.tree.getHalfCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.tree.getCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 初始话信息按钮
    initialise() {
      this.$refs.initalize.initalizeAdd(this.multipleSelection[0].id, this.multipleSelection[0].id)
    },
    // 查看按钮功能
    lookBtn() {
      this.$refs.details.detailsItem(this.multipleSelection[0].id)
    },
    // 企业树形数据筛选
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    // 节点单击事件
    handleNodeClick(data) {
      this.filters.province = ''
      this.filters.city = ''
      this.filters.area = ''
      const { count } = data
      switch (count) {
        case 0:
          this.filters.province = data.value
          break
        case 1:
          this.filters.city = data.value
          break
        case 2:
          this.filters.area = data.value
          break
      }
      this.$nextTick(() => {
        // 使树筛选时选中的节点高亮显示
        this.currentColor = true
        this.$refs.tree.setCurrentKey(data.value)
      })
      this.getList()
    }
  }
}
</script>

<style scoped>
.grid-content {
  border-radius: 4px;
  min-height: 36px;
  height:30px; line-height:30px;
  text-align: left;
  padding-left: 10px;
  font-size: 14px;
  font-weight:bolder;
  margin-bottom: 20px;
}
.bg-purple {
  background: #FFEEDD;
  color:#0a2140;
}
</style>
